package com.myorg.domain;

import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

import com.myorg.util.ConstantsToBeExternalized;
import com.myorg.util.HashFunctionHelper;

public class EmailDelimiter {
	private String key;
	private String hashValue;
	private Serializable[] infos;

	public EmailDelimiter(String key, Serializable... infos) {
		super();

		if (key == null || "".equals(key.trim())) {
			throw new IllegalStateException("<key> cannot be null.");
		}

		this.key = key.trim();
		this.infos = infos;
	}

	public String getKey() {
		return key;
	}

	public Serializable[] getInfos() {
		return infos;
	}

	private String getHashValue() throws UnsupportedEncodingException, NoSuchAlgorithmException {
		if (hashValue == null) {
			hashValue = HashFunctionHelper.getHash(key, HashFunctionHelper.getSalt());
		}
		return hashValue;
	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		try {
			sb.append("$").append(key).append(",").append(getHashValue());
			if (infos != null) {
				for (Serializable info : infos) {
					sb.append(",").append(info);
				}
			}
			sb.append("$");
		} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}

		return sb.toString();
	}

	public static String getEmailIdIfDelimitor(String del) {
		if (del != null && del.length() > 2 && '$' == del.charAt(0) && '$' == del.charAt(del.length() - 1)) {
			try {
				String[] arr = del.split(",");
				if (arr.length < 2) {
					return null;
				}
				if (ConstantsToBeExternalized.EMAIL_DELIMITER_FAST_TRACK) {
					return arr[0].substring(1);
				} else {
					EmailDelimiter d = new EmailDelimiter(arr[0].substring(1));
					String hashedValue = d.getHashValue();
					String origHashValue = arr[1]
							.substring(0, (arr.length > 2 ? arr[1].length() : arr[1].length() - 1));
					if (hashedValue.equals(origHashValue)) {
						return d.getKey();
					}
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
				throw new RuntimeException(e); // Zero tolerance on surprise
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				throw new RuntimeException(e); // Zero tolerance on surprise
			}
		}
		return null;
	}
}
